const express = require('express');
const router = express.Router();
const { pool } = require('../config/db');

// 获取简历列表
router.get('/list', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT id, name, title, contact, email, location, created_at, updated_at FROM resumes ORDER BY id DESC');
    res.json({ resumes: rows });
  } catch (err) {
    res.status(500).json({ message: '数据库查询失败', error: err.message });
  }
});

// 获取单份简历
router.get('/:id', async (req, res) => {
  try {
    const id = req.params.id;
    const [rows] = await pool.query('SELECT * FROM resumes WHERE id=?', [id]);
    if (!rows.length) return res.status(404).json({ message: '简历不存在' });
    const r = rows[0];
    r.education = r.education ? JSON.parse(r.education) : [];
    r.experience = r.experience ? JSON.parse(r.experience) : [];
    r.skills = r.skills ? JSON.parse(r.skills) : [];
    r.projects = r.projects ? JSON.parse(r.projects) : [];
    res.json(r);
  } catch (err) {
    res.status(500).json({ message: '查询失败', error: err.message });
  }
});

// 新增简历
router.post('/', async (req, res) => {
  try {
    const { name, title, contact, email, location, education, experience, skills, projects } = req.body;
    const [result] = await pool.query(
      'INSERT INTO resumes (name, title, contact, email, location, education, experience, skills, projects, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())',
      [name, title, contact, email, location, JSON.stringify(education), JSON.stringify(experience), JSON.stringify(skills), JSON.stringify(projects)]
    );
    res.status(201).json({ message: '简历保存成功', resumeId: result.insertId });
  } catch (err) {
    res.status(500).json({ message: '保存失败', error: err.message });
  }
});

// 编辑简历
router.put('/:id', async (req, res) => {
  try {
    const id = req.params.id;
    const { name, title, contact, email, location, education, experience, skills, projects } = req.body;
    const [result] = await pool.query(
      'UPDATE resumes SET name=?, title=?, contact=?, email=?, location=?, education=?, experience=?, skills=?, projects=?, updated_at=NOW() WHERE id=?',
      [name, title, contact, email, location, JSON.stringify(education), JSON.stringify(experience), JSON.stringify(skills), JSON.stringify(projects), id]
    );
    if (result.affectedRows === 0) return res.status(404).json({ message: '简历不存在' });
    res.json({ message: '简历更新成功' });
  } catch (err) {
    res.status(500).json({ message: '更新失败', error: err.message });
  }
});

// 删除简历
router.delete('/:id', async (req, res) => {
  try {
    const id = req.params.id;
    const [result] = await pool.query('DELETE FROM resumes WHERE id=?', [id]);
    if (result.affectedRows === 0) return res.status(404).json({ message: '简历不存在' });
    res.json({ message: '简历删除成功' });
  } catch (err) {
    res.status(500).json({ message: '删除失败', error: err.message });
  }
});

module.exports = router; 